package com.mz.ieann.aide.dialog

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import com.mz.ieann.dokit.utils.LogUtils

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> des
 * <p>
 *
 * @author Created by zhangmz90
 * @date on 2021 2021/11/14 13:39
 */
object PermissionsHelper {

    private const val PERMISSION_RESULT_CODE = 0x1001

    /**
     * manifest.xml添加的权限
     */
    private var manifestPermissions : Array<String>? = null

    /**
     * 待申请的权限
     */
    private var permissions = arrayListOf<String>()

    /**
     * 被用户拒绝的权限
     */
    private var denyPermissions = arrayListOf<String>()


    /**
     * 检查权限是否已经授予
     * return PackageManager.PERMISSION_GRANTED 已授予
     *        PackageManager.PERMISSION_DENIED 未授予
     */
    fun checkPermissions(con : FragmentActivity, vararg p: String?) {
        denyPermissions.clear()
        permissions.addAll(p.filterNotNull())
        checkNextPermission(con)
    }

    /**
     * 检查下一个权限
     */
    private fun checkNextPermission(con : FragmentActivity) {
        val permission = if (permissions.isNullOrEmpty()) {
            dealDenyPermission(con)
            return
        } else {
            permissions[0]
        }
        permissions.remove(permission)
        val manifestPermissions = readManifestPermission(con)
        if (manifestPermissions?.contains(permission) == false){
            LogUtils.e("Please ensure $permission has been added to the manifest.xml")
            checkNextPermission(con)
            return
        }
        requestPermission(con, permission)
    }

    /**
     * 单独申请权限
     */
    private fun requestPermission(con : FragmentActivity, permission : String){
        if (ContextCompat.checkSelfPermission(con, permission) == PackageManager.PERMISSION_GRANTED){
            checkNextPermission(con)
            return
        }
        // 权限未授予
        if (ContextCompat.checkSelfPermission(con, permission) == PackageManager.PERMISSION_DENIED){
            // 权限被用户拒绝
            if (!ActivityCompat.shouldShowRequestPermissionRationale(con, permission)){
                denyPermissions.add(permission)
                checkNextPermission(con)
                return
            }
            // 去申请权限
            ActivityCompat.requestPermissions(con, arrayOf(permission), PERMISSION_RESULT_CODE)
        }
    }

    /**
     * 处理权限申请结果
     */
    fun requestPermissionResult(con : FragmentActivity, requestCode: Int, p: Array<out String>, grantResults: IntArray){
        if (requestCode != PERMISSION_RESULT_CODE || p.size != grantResults.size){
            LogUtils.e("request permission result error")
            return
        }
        for (i in p.indices){
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED){
                denyPermissions.add(p[i])
            }
            checkNextPermission(con)
        }
    }

    /**
     * 被用户拒绝的权限系统无法自动弹出，需要跳转设置页手动打开
     */
    private fun dealDenyPermission(con: FragmentActivity){
        if (denyPermissions.isNotEmpty()){
            val message = StringBuilder()
            for (i in denyPermissions.indices){
                message.append("${PermissionsData.permissionMap[denyPermissions[i]]};")
            }
            Log.v(PermissionsHelper::class.java.simpleName, "$message 权限未被授予")
            DialogFactory.showWarning(
                con,
                "$message 等权限未被授予，点击确认，可跳转系统设置重新配置"){
                openPermissionSetting(con)
            }
        }
    }

    /**
     * 读取manifest.xml中申请的所有权限
     */
    private fun readManifestPermission(con : Context) : Array<String>? {
        if (manifestPermissions?.isNotEmpty() == true){
            return manifestPermissions
        }
        return runCatching {
            val packageInfo = con.packageManager.getPackageInfo(con.packageName, PackageManager.GET_PERMISSIONS)
            packageInfo.requestedPermissions
        }.getOrNull()
    }

    /**
     * 打开权限设置页面
     */
    private fun openPermissionSetting(con : Context){
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.parse("package:${con.packageName}")
        con.startActivity(intent)
    }

}